/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.jrcrm.service.business;

import net.dgg.dggcloud.core.util.DateUtil;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.base.SessionManager;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.common.pagination.PageData;
import net.dgg.dggcloud.service.dao.user.UserDao;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.constant.BusinessConstant;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerRecordConstant;
import net.dgg.dggcloud.service.jrcrm.constant.PageBusinessConstant;
import net.dgg.dggcloud.service.jrcrm.dao.business.BusinessDao;
import net.dgg.dggcloud.service.jrcrm.dao.cms.RuleConfigDao;
import net.dgg.dggcloud.service.jrcrm.entity.business.Business;
import net.dgg.dggcloud.service.jrcrm.entity.cms.RuleConfig;
import net.dgg.dggcloud.service.jrcrm.entity.customer.ReturnVisitCustomer;
import net.dgg.dggcloud.service.jrcrm.service.cms.CustomerRecordService;
import net.dgg.dggcloud.service.jrcrm.service.customer.ReturnVisitCustomerService;
import net.dgg.dggcloud.service.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName 〈BusinessPageAbilityService>
 * @Description 商机首页统计service
 * @Author 罗金
 * @Date 2017/11/22 11:49
 */
@Service
public class BusinessPageAbilityService extends BaseService {
    @Autowired
    private BusinessDao businessDao;
    @Autowired
    private UserDao userDao;
    @Resource
    private CustomerRecordService customerRecordService;
    @Resource
    private ReturnVisitCustomerService returnVisitCustomerService;
    @Autowired
    private UserService userService;
    @Autowired
    private RuleConfigDao ruleConfigDao;
    @Resource
    private BusinessService businessService;

    /**

     * 首页统计
     * @param paramMap
     * @param userIds
     * @param  orgIds  部门ID
     * @return
     */
    public Map<String,Object>  generateConditionByMap(Map paramMap,String orgIds,String userIds) {
        Map<String,Object> map  = new HashMap();
        String code = null == paramMap.get("code") ? "" : paramMap.get("code").toString();
        //新增资源统计
        if(code.equals(PageBusinessConstant.CODE_1)){
            paramMap.put("followerOrganizationId",orgIds);
            //当前跟进人ID
            paramMap.put("followerId",userIds);
            //公司资源
            paramMap.put("opportunitytypeCode","'"+BusinessConstant.BUS_OPP_1+"'");
            //第一次分配时间
            paramMap.put("firstDistributionTime","1");
            int i = businessDao.countPageBusinessByMap(paramMap);
            map.put("dataobject",i);
        }else if (code.equals(PageBusinessConstant.CODE_2)){//自主开发
            paramMap.put("followerOrganizationId",orgIds);
            //当前跟进人ID
            paramMap.put("followerId",userIds);
            //自开发
            paramMap.put("opportunitytypeCode","'"+BusinessConstant.BUS_OPP_3+"','"+BusinessConstant.BUS_OPP_2+"'");
            //商机为个人库
            paramMap.put("businessLocation", BusinessConstant.BUS_STORE_EMP);
            //第一次分配时间
            paramMap.put("createTime","1");
            int i = businessDao.countPageBusinessByMap(paramMap);
            map.put("dataobject",i);
        }else if (code.equals(PageBusinessConstant.CODE_3)){//掉库
            paramMap.put("followerOrganizationId",orgIds);
            //当前跟进人ID
            paramMap.put("followerId",userIds);
            //最新掉库时间
            paramMap.put("createTime","1");
            paramMap.put("type","out");
            paramMap.put("userId",userIds);
            //部门ids
            paramMap.put("userOrgId",orgIds);
            int i = businessDao.countBusinessRecordByMap(paramMap);
            map.put("dataobject",i);
        }else if (code.equals(PageBusinessConstant.CODE_13)){//签单  paramMap.put("followerOrganizationId",orgIds);
            //当前跟进人ID
            paramMap.put("createTime","1");
            paramMap.put("createrOrgId", orgIds);
            paramMap.put("createrId",userIds);
            paramMap.put("recordType","'"+CustomerRecordConstant.BUS_OPERATE_ORDER+"'");//签单
            int i = businessDao.countBusinessRecordByMap(paramMap);
            //int i = businessDao.countOrderBusinessByMap(paramMap);
            map.put("dataobject",i);
        } else if (code.equals(PageBusinessConstant.CODE_4)){//客户上门business_stage
            paramMap.put("followerOrganizationId",orgIds);
            //当前跟进人ID
            paramMap.put("followerId",userIds);
            //预约上门
            paramMap.put("lastFollowTime","lastFollowTime");
            //当前阶段为客户上门
            paramMap.put("businessStage",BusinessConstant.BUS_NEXT_FOLLOW_STAGE_CODE_4);
            //商机为个人库
            paramMap.put("businessLocation", BusinessConstant.BUS_STORE_EMP);
            //状态为跟进中
            paramMap.put("businessStatus","'"+BusinessConstant.BUS_STATUS_FOLLOWING+"'");
            //操作code
            paramMap.put("businessOperate","'"+CustomerRecordConstant.BUS_OPERATE_FOLLOW+"','"+CustomerRecordConstant.BUS_OPERATE_OWN_DEVELOP+"'");
            int i = businessDao.countPageBusinessByMap(paramMap);
            map.put("dataobject",i);
        } else if (code.equals(PageBusinessConstant.CODE_15)){//客户预约上门
            paramMap.put("followerOrganizationId",orgIds);
            //当前跟进人ID
            paramMap.put("followerId",userIds);
            //预约上门
            paramMap.put("nextFollowTime","nextFollowTime");
            //下次跟进阶段为预约上门
            paramMap.put("nextFollowStage",BusinessConstant.BUS_NEXT_STAGE_CODE_0);
            //商机为个人库
            paramMap.put("businessLocation", BusinessConstant.BUS_STORE_EMP);
            //状态为跟进中
            paramMap.put("businessStatus","'"+BusinessConstant.BUS_STATUS_FOLLOWING+"'");
            //操作code
            paramMap.put("businessOperate","'"+CustomerRecordConstant.BUS_OPERATE_FOLLOW+"','"+CustomerRecordConstant.BUS_OPERATE_OWN_DEVELOP+"','"+CustomerRecordConstant.BUS_OPERATE_ORDER_BACK+"'");
            int i = businessDao.countPageBusinessByMap(paramMap);
            map.put("dataobject",i);
        }else if(code.equals(PageBusinessConstant.CODE_5)){//今日待跟进
            paramMap.put("followerOrganizationId",orgIds);
            //当前跟进人ID
            paramMap.put("followerId",userIds);
            //商机为个人库
            paramMap.put("businessLocation", BusinessConstant.BUS_STORE_EMP);
            //状态为跟进中
            paramMap.put("businessStatus","'"+BusinessConstant.BUS_STATUS_FOLLOWING+"'");
            //操作code
            paramMap.put("businessOperate","'"+CustomerRecordConstant.BUS_OPERATE_FOLLOW+"','"+CustomerRecordConstant.BUS_OPERATE_OWN_DEVELOP+"'");
            paramMap.put("todayFollowing","1");
            int i = businessDao.countPageBusinessByMap(paramMap);
            map.put("dataobject",i);

        }else if (code.equals(PageBusinessConstant.CODE_7)){//明天掉库
            paramMap.put("followerOrganizationId",orgIds);
            //当前跟进人ID
            paramMap.put("followerId",userIds);
            //商机为个人库
            paramMap.put("businessLocation", BusinessConstant.BUS_STORE_EMP);
            //状态为跟进中
            paramMap.put("businessStatus","'"+BusinessConstant.BUS_STATUS_FOLLOWING+"'");
            //操作code
            paramMap.put("businessOperate","'"+CustomerRecordConstant.BUS_OPERATE_FOLLOW+"','"+CustomerRecordConstant.BUS_OPERATE_OWN_DEVELOP+"'");
            paramMap.put("tomorrow", 1);
            int i = businessDao.countPageBusinessByMap(paramMap);
            map.put("dataobject",i);
        }else if (code.equals(PageBusinessConstant.CODE_14)){//明天掉库 贷款金额大于30万
            paramMap.put("followerOrganizationId",orgIds);
            //当前跟进人ID
            paramMap.put("followerId",userIds);
            //商机为个人库
            paramMap.put("businessLocation", BusinessConstant.BUS_STORE_EMP);
            //状态为跟进中
            paramMap.put("businessStatus","'"+BusinessConstant.BUS_STATUS_FOLLOWING+"'");
            //操作code
            paramMap.put("businessOperate","'"+CustomerRecordConstant.BUS_OPERATE_FOLLOW+"','"+CustomerRecordConstant.BUS_OPERATE_OWN_DEVELOP+"'");
            paramMap.put("tomorrow", 1);
            paramMap.put("loanAmount",30*1000000);
            int i = businessDao.countPageBusinessByMap(paramMap);
            map.put("dataobject",i);
        } else if(code.equals(PageBusinessConstant.CODE_8)){ //2天后掉库
            paramMap.put("followerOrganizationId",orgIds);
            //当前跟进人ID
            paramMap.put("followerId",userIds);
            //商机为个人库
            paramMap.put("businessLocation", BusinessConstant.BUS_STORE_EMP);
            //状态为跟进中
            paramMap.put("businessStatus","'"+BusinessConstant.BUS_STATUS_FOLLOWING+"'");
            //操作code
            paramMap.put("businessOperate","'"+CustomerRecordConstant.BUS_OPERATE_FOLLOW+"','"+CustomerRecordConstant.BUS_OPERATE_OWN_DEVELOP+"'");
            paramMap.put("twoDay", 2);
            int i = businessDao.countPageBusinessByMap(paramMap);
            map.put("dataobject",i);
        }else if(code.equals(PageBusinessConstant.CODE_9)){ //逾期跟进
            paramMap.put("followerOrganizationId",orgIds);
            //当前跟进人ID
            paramMap.put("followerId",userIds);
            //商机为个人库
            paramMap.put("businessLocation", BusinessConstant.BUS_STORE_EMP);
            //状态为跟进中
            paramMap.put("businessStatus","'"+BusinessConstant.BUS_STATUS_FOLLOWING+"'");
            //操作code
            paramMap.put("businessOperate","'"+CustomerRecordConstant.BUS_OPERATE_FOLLOW+"','"+CustomerRecordConstant.BUS_OPERATE_OWN_DEVELOP+"'");
            paramMap.put("overdue","1");
            int i = businessDao.countPageBusinessByMap(paramMap);
            map.put("dataobject",i);
        }else if(code.equals(PageBusinessConstant.CODE_10)){  //离职待移交
            //商务已经离职，且商机还在个人库
            paramMap.put("businessLocation", BusinessConstant.BUS_STORE_EMP);
            Map userMap = new HashMap();
            User loginUser = SessionManager.getCurrentUser();
            userMap.put("rootOrgId", loginUser.getOrgId());
            userMap.put("userState", 2);
            userMap.put("pageSize", 10000);
            PageData<Map> users = userService.searchUser(userMap);//查询离职的商务列表
            String followerIds = "-1";
            if (null != users && null != users.getData() && !users.getData().isEmpty()) {
                StringBuffer ids = new StringBuffer();
                for (Map mapu : users.getData()) {
                    ids.append(mapu.get("userid").toString()).append(",");
                }
                if (ids.length() > 0) {
                    followerIds = ids.substring(0, ids.lastIndexOf(","));
                }
            }
            paramMap.put("followerId", followerIds);
            int i = businessDao.countPageBusinessByMap(paramMap);
            map.put("dataobject",i);
        }else if(code.equals(PageBusinessConstant.CODE_11)){
            paramMap.put("businessOperate", "'" + CustomerRecordConstant.BUS_OPERATE_NOCALL_LEADER + "'");//未首电移交经理
            paramMap.put("followerOrgId",orgIds);//商机的当前跟进部门为当前人部门或以下部门
            int i = businessDao.countPageBusinessByMap(paramMap);
            map.put("dataobject",i);
        }else if(code.equals(PageBusinessConstant.CODE_12)){  //二次咨询
            paramMap.put("recordType", "'" + CustomerRecordConstant.REMIND_FOLLOWER + "'");//2次咨询
            paramMap.put("toUserOrgIds",orgIds);//部门
            paramMap.put("toUserId",userIds);//userid
            paramMap.put("startTime",DateUtil.dateToString(new Date(),"yyyy-MM-dd"));//startTime
            paramMap.put("endTime",DateUtil.dateToString(new Date(),"yyyy-MM-dd"));//endTime
            int i = businessDao.countBusinessRecordByMap(paramMap);
            map.put("dataobject",i);
        }else if (code.equals(PageBusinessConstant.CODE_16)){   //掉库率
            //当前跟进人ID
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            paramMap.put("followerId",userIds);
            paramMap.put("dpcreateTime",df.format(new Date()));
            List<Map> list = businessDao.countSelectTodayDropBusiness(paramMap);
            int i = list.size();
            int nowCount = businessDao.countFollowerBusiness(paramMap);
            BigDecimal point = new BigDecimal(100);
            BigDecimal rate= new BigDecimal(0);
            if(i>0) {
                 rate = new BigDecimal(i).divide(new BigDecimal(nowCount + i), 2, BigDecimal.ROUND_HALF_UP).multiply(point);//计算掉库率
                 map.put("dataobject",rate.toString()+"%");
            }else{
                 map.put("dataobject",rate.toString()+"%");
            }
            map.put("dataobject",rate.toString()+"%");
        }else if (code.equals(PageBusinessConstant.CODE_17)){ //掉库率超个80%的商务
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            paramMap.put("dpcreateTime",df.format(new Date()));
            map.put("dataobject",countBusinessYesterdayDropRate(paramMap,orgIds)+"");
        }else if(code.equals(PageBusinessConstant.CODE_18)) {//已签单今日待跟进
            paramMap.put("createrOrgId", orgIds);
            //当前跟进人ID
            paramMap.put("createrId", userIds);
            //商机为个人库
            paramMap.put("businessLocation", BusinessConstant.BUS_STORE_EMP);
            paramMap.put("todayFollowing", "1");
            Integer i = businessService.countOrderBusinessByMap(paramMap);
            map.put("dataobject", i);

        }
        map.put("message","操作成功");
        map.put("result","0");
        return map;

    }




    /**
     * 计算事业部昨日的掉库商机，并对超过掉库率的商机跟进人进行强制不接单设置
     *
     * @param orgId 事业部id
     */
    public int countBusinessYesterdayDropRate(Map map,String orgId) {
        BigDecimal point = new BigDecimal(100);
        int i = 0;
        map.put("followerOrganizationId",orgId+"");
//        String rc = ruleConfigDao.getRuleConfigByMap(map);
            List<Map> list = businessDao.countSelectTodayDropBusiness(map);
            //计算出商机跟进人掉库商机数量，再统计这个人总共有多少条商机，掉库率 = 掉库数量/（掉库数+当前库数）
            Map<Long, User> data = new HashMap<>();
            for (Map business : list) {
                if (data.containsKey(business.get("followerId"))) {
                    User u = data.get(business.get("followerId"));
                    u.setLocked(u.getLocked()+1);
                    data.put(Long.parseLong(business.get("followerId")+""),  u);
                } else {
                    User u = new User();
                    u.setId(Long.parseLong(business.get("followerId")==null?"-1":business.get("followerId")+""));
                    u.setOrgId(Long.parseLong(business.get("followerOrganizationId")==null?"-1":business.get("followerOrganizationId")+""));
                    u.setDeptId(Long.parseLong(business.get("businessOrganizationId")==null?"-1":business.get("businessOrganizationId")+""));
                    u.setLocked(1);//暂时用该字段存用户的掉库商机数量
                    data.put(Long.parseLong(business.get("followerId")==null?"-1":business.get("followerId")+""), u);
                }
            }
            for (Long userId : data.keySet()) {
                map.put("followerId",userId+"");
                Integer nowCount = businessDao.countFollowerBusiness(map);//统计商务现在库中的商机数量
                User u = data.get(userId);
                BigDecimal rate = new BigDecimal(u.getLocked()).divide(new BigDecimal(nowCount + u.getLocked()), 2, BigDecimal.ROUND_HALF_UP).multiply(point);//计算掉库率
                if (rate.compareTo(new BigDecimal(80)) > -1) {//掉库率大于了设置的值
                  ++i;
                }
            }

          return i;
        }


    /**
     *
     *
     * @param orgId 事业部id
     */
    public List<Map> countBusinessYesterdayDropNum(Map map,String orgId) {
        BigDecimal point = new BigDecimal(100);
        List<Map>  listMap = new ArrayList<>();
        int i = 0;
        map.put("followerOrganizationId",orgId+"");
//        String rc = ruleConfigDao.getRuleConfigByMap(map);
        List<Map> list = businessDao.countSelectTodayDropBusiness(map);
        //计算出商机跟进人掉库商机数量，再统计这个人总共有多少条商机，掉库率 = 掉库数量/（掉库数+当前库数）
        Map<Long, User> data = new HashMap<>();
        for (Map business : list) {
            if (data.containsKey(business.get("followerId"))) {
                User u = data.get(business.get("followerId"));
                u.setLocked(u.getLocked()+1);
               // u.setName();
                data.put(Long.parseLong(business.get("followerId")+""),  u);
            } else {
                User u = new User();
                u.setId(Long.parseLong(business.get("followerId")==null?"-1":business.get("followerId")+""));
                u.setOrgId(Long.parseLong(business.get("followerOrganizationId")==null?"-1":business.get("followerOrganizationId")+""));
                u.setDeptId(Long.parseLong(business.get("businessOrganizationId")==null?"-1":business.get("businessOrganizationId")+""));
                u.setLocked(1);//暂时用该字段存用户的掉库商机数量
                data.put(Long.parseLong(business.get("followerId")==null?"-1":business.get("followerId")+""), u);
            }
        }
        for (Long userId : data.keySet()) {
            map.put("followerId",userId+"");
            Integer nowCount = businessDao.countFollowerBusiness(map);//统计商务现在库中的商机数量

            User u = data.get(userId);
            Map newMap = new HashMap();
            newMap.put("repertory",nowCount);
            newMap.put("drop",u.getLocked());

            BigDecimal rate = new BigDecimal(u.getLocked()).divide(new BigDecimal(nowCount + u.getLocked()), 2, BigDecimal.ROUND_HALF_UP).multiply(point);//计算掉库率
            newMap.put("dropRate",rate);
            if (rate.compareTo(new BigDecimal(80)) > -1) {//掉库率大于了设置的值
                User user = userDao.find4Id(userId);
                newMap.put("name",user.getName());
                newMap.put("locked",user.getLocked());
                listMap.add(newMap);
            }
        }
        return listMap;
    }

}
